'use strict';

// 云对象名：my-service
module.exports = {
  /**
   * 获取我的规则
   * @param {object} params - 参数对象
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @param {number} params.page - 页码
   * @param {number} params.limit - 每页数量
   * @returns {object} 我的规则列表
   */
  async getMyRules(params = {}) {
    try {
      const db = uniCloud.database();
      
      const { userId, token, page = 1, limit = 10 } = params;
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询我的规则（包括收藏的和创建的）
      const favoriteRulesResult = await db.collection('user_favorites')
        .where({
          user_id: currentUserId,
          resource_type: 'rule'
        })
        .get();
      
      const favoriteRuleIds = favoriteRulesResult.data.map(item => item.resource_id);
      
      // 构建查询条件
      const where = {
        $or: [
          { userId: currentUserId },
          { creator_id: currentUserId },
          { _id: db.command.in(favoriteRuleIds) }
        ]
      };
      
      // 查询规则列表
      const rulesResult = await db.collection('rule_contents')
        .where(where)
        .orderBy('create_date', 'desc')
        .skip(skip)
        .limit(limit)
        .get();
      
      // 查询总数
      const countResult = await db.collection('rule_contents')
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: rulesResult.data || [],
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取我的规则失败:', error);
      return {
        code: -1,
        message: '获取失败: ' + error.message
      };
    }
  },

  /**
   * 获取我的视频
   * @param {object} params - 参数对象
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @param {number} params.page - 页码
   * @param {number} params.limit - 每页数量
   * @returns {object} 我的视频列表
   */
  async getMyVideos(params = {}) {
    try {
      const db = uniCloud.database();
      
      const { userId, token, page = 1, limit = 10 } = params;
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询我的视频（包括收藏的和创建的）
      const favoriteVideosResult = await db.collection('user_favorites')
        .where({
          user_id: currentUserId,
          resource_type: 'video'
        })
        .get();
      
      const favoriteVideoIds = favoriteVideosResult.data.map(item => item.resource_id);
      
      // 构建查询条件
      const where = {
        $or: [
          { userId: currentUserId },
          { creator_id: currentUserId },
          { _id: db.command.in(favoriteVideoIds) }
        ]
      };
      
      // 查询视频列表
      const videosResult = await db.collection('learning_videos')
        .where(where)
        .orderBy('create_date', 'desc')
        .skip(skip)
        .limit(limit)
        .get();
      
      // 查询总数
      const countResult = await db.collection('learning_videos')
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: videosResult.data || [],
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取我的视频失败:', error);
      return {
        code: -1,
        message: '获取失败: ' + error.message
      };
    }
  },

  /**
   * 获取用户学习列表
   * @param {object} params - 参数对象
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @param {string} params.type - 类型（可选）
   * @param {number} params.page - 页码
   * @param {number} params.pageSize - 每页数量
   * @param {boolean} params.completed - 完成状态筛选
   * @returns {object} 学习列表
   */
  async getUserLearningList(params = {}) {
    try {
      const db = uniCloud.database();
      
      const { userId, token, type, page = 1, pageSize = 10, completed } = params;
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 构建查询条件
      const where = { user_id: currentUserId };
      if (type) {
        where.resource_type = type;
      }
      
      // 根据完成状态筛选
      if (completed !== undefined) {
        if (completed) {
          where.progress = db.command.gte(100);
        } else {
          where.progress = db.command.lt(100);
        }
      }
      
      // 计算跳过数量
      const skip = (page - 1) * pageSize;
      
      // 查询学习记录
      const learningResult = await db.collection('learning_records')
        .where(where)
        .orderBy('last_learn_time', 'desc')
        .skip(skip)
        .limit(pageSize)
        .get();
      
      // 查询总数
      const countResult = await db.collection('learning_records')
        .where(where)
        .count();
      
      // 获取关联的资源详情
      const learningRecords = learningResult.data || [];
      const enrichedRecords = [];
      
      for (const record of learningRecords) {
        let resourceDetail = null;
        
        try {
          switch (record.resource_type) {
            case 'rule':
              const ruleResult = await db.collection('rule_contents').doc(record.resource_id).get();
              resourceDetail = ruleResult.data;
              break;
            case 'video':
              const videoResult = await db.collection('learning_videos').doc(record.resource_id).get();
              resourceDetail = videoResult.data;
              break;
            case 'exam':
              const examResult = await db.collection('exam_papers').doc(record.resource_id).get();
              resourceDetail = examResult.data;
              break;
          }
        } catch (error) {
          console.error('获取资源详情失败:', error);
        }
        
        // 构建返回的记录格式，匹配前端期望的字段
        const enrichedRecord = {
          _id: record._id,
          content_id: record.resource_id,
          content_type: record.resource_type,
          title: resourceDetail?.title || '未知内容',
          completed: record.progress >= 100,
          is_completed: record.progress >= 100,
          last_learn_date: record.last_learn_time ? new Date(record.last_learn_time).getTime() : null,
          duration: record.duration || 0,
          progress: record.progress || 0,
          resource_detail: resourceDetail
        };
        
        enrichedRecords.push(enrichedRecord);
      }
      
      return {
        code: 0,
        message: '获取成功',
        data: {
          list: enrichedRecords,
          total: countResult.total,
          page: page,
          pageSize: pageSize
        }
      };
    } catch (error) {
      console.error('获取用户学习列表失败:', error);
      return {
        code: -1,
        message: '获取失败: ' + error.message
      };
    }
  },

  /**
   * 获取裁判员信息
   * @param {object} params - 参数对象
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @returns {object} 裁判员信息
   */
  async getRefereeInfo(params = {}) {
    try {
      const db = uniCloud.database();
      
      const { userId, token } = params;
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 查询用户基本信息
      const userResult = await db.collection('users').doc(currentUserId).get();
      if (!userResult.data || userResult.data.length === 0) {
        return {
          code: -1,
          message: '用户不存在'
        };
      }
      
      const userInfo = Array.isArray(userResult.data) ? userResult.data[0] : userResult.data;
      
      // 查询裁判员认证信息
      let refereeCredential = null;
      const refereeResult = await db.collection('referee_credentials').where({
        user_id: currentUserId
      }).get();
      
      if (refereeResult.data && refereeResult.data.length > 0) {
        refereeCredential = refereeResult.data[0];
      }
      
      // 查询考试记录统计
      const examRecordsResult = await db.collection('exam_records').where({
        user_id: currentUserId
      }).get();
      
      const examRecords = examRecordsResult.data || [];
      const totalExams = examRecords.length;
      const passedExams = examRecords.filter(record => record.status === 'passed').length;
      
      // 查询学习记录统计
      const learningRecordsResult = await db.collection('learning_records').where({
        user_id: currentUserId
      }).get();
      
      const learningRecords = learningRecordsResult.data || [];
      const totalLearningTime = learningRecords.reduce((sum, record) => sum + (record.duration || 0), 0);
      
      // 构建返回数据
      const refereeInfo = {
        _id: userInfo._id,
        username: userInfo.username,
        nickname: userInfo.nickname,
        email: userInfo.email,
        phone: userInfo.phone,
        role: userInfo.role,
        status: userInfo.status,
        create_date: userInfo.create_date,
        last_login_date: userInfo.last_login_date,
        credential_status: refereeCredential?.status || 'none',
        referee_level: refereeCredential?.level || null,
        certificate_number: refereeCredential?.certificate_number || null,
        statistics: {
          total_exams: totalExams,
          passed_exams: passedExams,
          pass_rate: totalExams > 0 ? Math.round((passedExams / totalExams) * 100) : 0,
          total_learning_time: totalLearningTime,
          learning_resources: learningRecords.length
        }
      };
      
      return {
        code: 0,
        message: '获取成功',
        data: refereeInfo
      };
    } catch (error) {
      console.error('获取裁判员信息失败:', error);
      return {
        code: -1,
        message: '获取裁判员信息失败: ' + error.message
      };
    }
  },

  /**
   * 获取轮播图
   * @returns {object} 轮播图列表
   */
  async getBanners() {
    try {
      const db = uniCloud.database();
      
      // 构建查询条件，排除已删除的公告
      const baseCondition = {
        status: db.command.neq('deleted'), // 排除已删除的公告
        isDeleted: db.command.neq(true)    // 同时检查isDeleted字段
      };
      
      // 首先尝试获取设置为在轮播显示的公告
      const bannerCondition = {
        ...baseCondition,
        showInBanner: true
      };
      
      console.log('轮播图查询条件:', JSON.stringify(bannerCondition));
      
      let bannerRes = await db.collection('notices').where(bannerCondition)
        .orderBy('publishDate', 'desc')
        .limit(5) // 限制返回5条轮播图
        .get();
      
      console.log('轮播查询结果:', JSON.stringify(bannerRes.data));
      
      // 如果没有找到符合条件的公告，获取最新的公告
      if (!bannerRes.data || bannerRes.data.length === 0) {
        console.log('没有找到设置为轮播的公告，获取最新公告');
        
        const fallbackCondition = {
          ...baseCondition,
          status: 'published' // 确保公告已发布且未删除
        };
        
        console.log('备用查询条件:', JSON.stringify(fallbackCondition));
        
        bannerRes = await db.collection('notices').where(fallbackCondition)
          .orderBy('publishDate', 'desc')
          .limit(5)
          .get();
        
        console.log('备用查询结果:', JSON.stringify(bannerRes.data));
      }
      
      // 对于没有banner图片的公告，分配默认图片
      const processed = bannerRes.data.map(item => {
        // 确保每个公告都有图片
        let imageUrl = '';
        if (item.bannerImage && item.bannerImage.url) {
          imageUrl = item.bannerImage.url;
        } else {
          // 根据公告类型分配默认图片
          if (item.type === 'activity') {
            imageUrl = 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-5fa97292-6ab3-4cb2-b482-4ea95de61eda/c4a6f63c-ae12-4a13-900e-14c3cebf6105.jpg';
          } else {
            imageUrl = 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-5fa97292-6ab3-4cb2-b482-4ea95de61eda/93ac0f42-ef0a-48c5-a9af-9c34a0fbf4c4.jpg';
          }
        }
        
        // 返回统一的轮播数据格式
        return {
          id: item._id,
          title: item.title || '',
          image: imageUrl,
          type: item.type || 'notice',
          publishDate: item.publishDate,
          url: `/packageNotice/Notice/notice-detail?id=${item._id}` // 添加跳转链接
        };
      });
      
      console.log('处理后的轮播数据:', JSON.stringify(processed));
      
      if (processed && processed.length > 0) {
        return {
          code: 0,
          message: '获取成功',
          data: processed
        };
      } else {
        // 如果没有任何数据，返回默认轮播图
        const defaultBanners = [
          {
            id: 'default1',
            title: '足球裁判培训',
            image: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-5fa97292-6ab3-4cb2-b482-4ea95de61eda/93ac0f42-ef0a-48c5-a9af-9c34a0fbf4c4.jpg',
            type: 'notice',
            url: '/pages/study/study'
          },
          {
            id: 'default2',
            title: '在线考试',
            image: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-5fa97292-6ab3-4cb2-b482-4ea95de61eda/93ac0f42-ef0a-48c5-a9af-9c34a0fbf4c4.jpg',
            type: 'notice',
            url: '/pages/exam/exam'
          },
          {
            id: 'default3',
            title: '学习资源',
            image: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-5fa97292-6ab3-4cb2-b482-4ea95de61eda/93ac0f42-ef0a-48c5-a9af-9c34a0fbf4c4.jpg',
            type: 'notice',
            url: '/pages/study/study'
          }
        ];
        
        return {
          code: 0,
          message: '获取成功',
          data: defaultBanners
        };
      }
    } catch (error) {
      console.error('获取轮播图失败:', error);
      return {
        code: -1,
        message: '获取轮播图失败: ' + error.message,
        data: []
      };
    }
  }
}; 